package com.yytek.common.client;

import com.yytek.common.client.base.*;


import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;


public class MutiMqClient implements MessageCallBack {

    //多层通配符常量
    private static final String MULTI_LEVEL_WILDCARD = "#";
    //单层通配符常量
    private static final String SINGLE_LAYER_WILDCARD = "+";


    private IMqClient client;

    private HashMap<String, List<MessageCallBack>> subMap;

    public MutiMqClient() {
        subMap = new HashMap<String, List<MessageCallBack>>();
    }

    public boolean isConnected() {
        if (client != null) {
            return client.isConnected();
        }
        return false;
    }

    public void init(MqConfig config) {
        client = MqClientFactory.getInstance().createMQTTClient(config);
        client.setMessageCallBack(this);
        client.open();
    }

    public synchronized void subscribe(String topic, MessageCallBack messageCallBack) {
        List<MessageCallBack> list = subMap.get(topic);
        if (list == null) {
            list = new ArrayList<MessageCallBack>();
            subMap.put(topic, list);
            client.subscribe(topic);
        }
        if (!list.contains(messageCallBack)) {
            list.add(messageCallBack);
        }
    }

    public synchronized void unsubscribe(String topic, MessageCallBack messageCallBack) {
        //不取消可以暂时不加
    }

    public void send(String topic, MqMessage msg) {
        if (msg != null && topic.endsWith("zip")) {
            client.publish(topic, MqFlaterZipUtil.zipString(msg.toString()));
        } else {
            client.publish(topic, msg);
        }

    }

    public void send(String topic, String msg) {
        if (msg != null && topic.endsWith("zip")) {
            client.publish(topic, MqFlaterZipUtil.zipString(msg));
        } else {
            client.publish(topic, msg);
        }
    }


    @Override
    public void onPublish(String topic, MqMessage msg, String destination) {
        List<MessageCallBack> list = null;
        list = subMap.get(topic);
        if (destination.indexOf(MULTI_LEVEL_WILDCARD) > -1 || destination.indexOf(SINGLE_LAYER_WILDCARD) > -1) {
            list = subMap.get(destination);
        }
        if (list != null && list.size() > 0) {
            if (topic.endsWith("zip")) {
                msg.setPayload(MqFlaterZipUtil.unzipString(msg.toString()).getBytes());
            }
            list.parallelStream().forEach(c -> c.onPublish(topic, msg, destination));
        }
    }
}
